<?php /*a:1:{s:60:"D:\projects\junhe\app\data\view\store\goods_models\form.html";i:1741796639;}*/ ?>
<form class="layui-form layui-card"  action="<?php echo sysuri(); ?>" onsubmit="return false" method="post">
    <div class="layui-card-body">
        <div class="layui-form-item">
            <label class="layui-form-label">绑定产品</label>
            <div class="layui-input-block">
                <select class="layui-select" required name="goods_id" lay-filter="goods_id" lay-search>
                    <option value="">-- 全部产品 --</option>
                    <?php foreach($goods_list as $v): ?>
                        <option <?php if($vo && $vo['goods_id'] == $v['id']): ?> selected <?php endif; ?> value="<?php echo htmlentities($v['id'],ENT_QUOTES); ?>"><?php echo htmlentities($v['title'],ENT_QUOTES); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">型号名称</label>
            <div class="layui-input-block">
                <input type="text" name="name" required lay-verify="required" value='<?php echo htmlentities((isset($vo['name']) && ($vo['name'] !== '')?$vo['name']:""),ENT_QUOTES); ?>' placeholder="请输入型号名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" >
            <label class="layui-form-label">参数</label>
            <button type="button" id="add_spec" class="layui-btn layui-btn-sm  layui-btn-normal"><i class="layui-icon layui-icon-addition"></i>  增加</button>
            <div class="layui-input-block">
                <table class="layui-table">
                    <thead>
                      <tr>
                        <th>类型</th>
                        <th>参数</th>
                        <th>操作</th>
                      </tr> 
                    </thead>
                    <tbody id="spec-tbody">
                        
                    </tbody>
                  </table>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">排序</label>
            <div class="layui-input-block">
                <input type="text" name="sort" required lay-verify="required" value='<?php echo htmlentities((isset($vo['sort']) && ($vo['sort'] !== '')?$vo['sort']:"1"),ENT_QUOTES); ?>' placeholder="请输入型号名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" >
            <label class="layui-form-label">图片</label>
            <div class="layui-input-block">
                <table class="layui-table layui-col-xs6">
                    <thead>
                    <tr>
                        <th class="text-center">上传图片</th>
                    </tr>
                    <tr>
                        <td width="90px" class="text-center"><input name="thumb" type="hidden" value="<?php echo htmlentities((isset($vo['thumb']) && ($vo['thumb'] !== '')?$vo['thumb']:''),ENT_QUOTES); ?>"></td>
                    </tr>
                    </thead>
                </table>
                <script>$('[name="thumb"]').uploadOneImage()</script>
            </div>
        </div>
       
      
      
    </div>

    <div class="hr-line-dashed"></div>
    <?php if(!(empty($vo['id']) || (($vo['id'] instanceof \think\Collection || $vo['id'] instanceof \think\Paginator ) && $vo['id']->isEmpty()))): ?><input type='hidden' value='<?php echo htmlentities($vo['id'],ENT_QUOTES); ?>' name='id'><?php endif; ?>

    <div class="layui-form-item text-center">
        <button class="layui-btn" lay-filter="goods_form" lay-submit >保存数据</button>
        <button class="layui-btn layui-btn-danger" type='button' data-confirm="确定要取消编辑吗？" data-close>取消编辑</button>
    </div>
</form>


<script src="/public/static/index.js"></script>
<script>
    
layui.use(['form', 'jquery'], function(){
    var form = layui.form;
    var $ = layui.jquery;
    var attributes = [];
    form.on('select(goods_id)', function(data){
        let goods_id = data.value;
        ajaxRequest("<?php echo url('store.goods_models/get_spec_by_goods'); ?>", {goods_id:goods_id}, 'get', this, function (response) {
            if (response.code === 1) {
                attributes = response.data;  // **更新全局变量**
                $('#spec-tbody').empty(); // 清空参数行
                form.render('select'); // 重新渲染下拉框
                console.log("获取的规格数据：", attributes);
            } else {
                attributes = [];
                layer.msg('获取规格失败', {icon: 2, time: 2000});
            }
        });
  
    });
    // 参数数据（假设已经通过 PHP 传递到前端）


    // 渲染参数选择下拉框
    function renderAttributeSelect() {
        var html = '<option value="">请选择参数</option>';
        attributes.forEach(function(attribute){
            html += `<option value="${attribute.id}" data-type="${attribute.type}">${attribute.name}</option>`;
        });
        return html;
    }

    // 添加参数行
    $('#add_spec').click(function(){
        if (attributes.length === 0) {
            layer.msg('请先选择商品，加载规格参数！', {icon: 2, time: 2000});
            return;
        }
        var html = `
            <tr class="spec-row">
                <td>
                    <select lay-search class="layui-select spec-type" lay-filter="spec-type">
                        ${renderAttributeSelect()}
                    </select>
                </td>
                <td class="spec-value-cell">
                    <!-- 参数值输入框或下拉框将动态插入到这里 -->
                </td>
                <td>
                    <button type="button" class="layui-btn layui-btn-danger layui-btn-sm delete-spec">删除</button>
                </td>
            </tr>
        `;
        $('#spec-tbody').append(html);
        form.render('select'); // 重新渲染下拉框
    });

    // 监听参数类型选择
    form.on('select(spec-type)', function(data){
        var attributeId = data.value;
        var attribute = attributes.find(function(item){
            return item.id == attributeId;
        });

        if (!attribute) {
            return;
        }

        var $row = $(data.elem).closest('.spec-row');
        var $valueCell = $row.find('.spec-value-cell');

        var html = '';
        if (attribute.type === 'input') {
            html = `<input type="text" name="spec[${attributeId}]" placeholder="请输入${attribute.name}" class="layui-input">`;
        } else if (attribute.type === 'select') {
            var optionsHtml = '<option value="">请选择' + attribute.name + '</option>';
            attribute.values.forEach(function(value){
                optionsHtml += `<option value="${value.id}">${value.value}</option>`;
            });
            html = `<select name="spec[${attributeId}]" class="layui-select">${optionsHtml}</select>`;
        }else if (attribute.type === 'checkbox') {
            // 多选框
            attribute.values.forEach(function(value) {
                html += `
                    <input type="checkbox" 
                        name="spec[${attributeId}][]" 
                        value="${value.id}" 
                        title="${value.value}" 
                        lay-skin="primary"
                        class="layui-input">
                `;
            });
           
        }

        $valueCell.html(html);
        form.render('select'); // 重新渲染下拉框
        form.render('checkbox');
    });

    // 删除参数行
    $(document).on('click', '.delete-spec', function(){
        $(this).closest('.spec-row').remove();
    });

    form.on('submit(goods_form)', function(data){
        var formData = data.field;
        var specs = [];
        var isValid = true; // 校验是否通过

        // 校验产品名称
        if (!formData.name || formData.name.trim() === '') {
            layer.msg('请输入型号名称');
            isValid = false;
            return false;
        }

        // 校验参数行
        $('#spec-tbody .spec-row').each(function(){
            var $row = $(this);
            var attributeId = $row.find('.spec-type').val();
            var $valueInput = $row.find('.spec-value-cell input, .spec-value-cell select');
            var value;
            // 判断是否是复选框
            if ($valueInput.attr('type') === 'checkbox') {
                // 多选框的值是一个数组
                value = [];
                $row.find('.spec-value-cell input[type="checkbox"]:checked').each(function() {
                    value.push($(this).val());
                });
                value = value.join(','); // 将数组转换为以逗号分隔的字符串
            } else {
                // 其他类型的值（输入框、下拉框、单选框）
                value = $valueInput.val();
            }
            if (!attributeId) {
                return layer.msg('请选择参数类型');
                isValid = false;
                return false;
            }

            if (!value || value.trim() === '') {
                var attributeName = $row.find('.spec-type option:selected').text();
                return layer.msg(`请填写或选择${attributeName}`);
                isValid = false;
                return false;
            }

            specs.push({
                attribute_id: attributeId,
                value: value
            });
        });

        if (!isValid) {
            return false; // 校验不通过，阻止提交
        }
        formData.specs = specs;
        ajaxRequest("<?php echo url('store.goods_models/add'); ?>", formData, 'POST', this, function (response) {
                layer.msg('操作成功', {icon: 1, time: 2000}, function() {
                    // 弹窗消失后跳转
						layer.closeAll()
                        location.reload()
					});
				});
        return false
    })

});
</script>
